#include "analysiswindow.h"
#include "ui_analysiswindow.h"
#include <QMessageBox>
//郝代码
AnalysisWindow::AnalysisWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AnalysisWindow)
{
    ui->setupUi(this);
}

AnalysisWindow::~AnalysisWindow()
{
    delete ui;
}

void AnalysisWindow::setIntersectionPoint(const QPointF &point)
{

    intersectionPoint = point;

    if (point.x() < 0 || point.y() < 0) {
        ui->titleLabel->setText("未找到有效交点");
        ui->analysisLabel->setText("请先在交易市场中生成有效曲线并确保存在交点。");
        return;
    }

    // 显示交点坐标
    ui->titleLabel->setText(QString("  ").arg(point.x(), 0, 'f', 2).arg(point.y(), 0, 'f', 2));

    // m_s1=a;
    // m_s2=b;


    // 生成分析内容
    QString analysis = QString("电力市场均衡分析:\n\n");
    analysis += QString("1. 均衡电量: %.1 单位\n").arg(m_s1, 0, 'f', 2);
    analysis += QString("2. 均衡电价: %.1 元/单位\n\n").arg(point.y(), 0, 'f', 2);
    analysis += "3. 市场解读:\n";
    analysis += "- 在该均衡点，供电量与购电量达到平衡\n";
    analysis += "- 此时的电价为市场可接受的合理价格\n";
    analysis += "- 若实际价格高于均衡电价，会出现供过于求的情况\n";
    analysis += "- 若实际价格低于均衡电价，会出现供不应求的情况";

    ui->analysisLabel->setText(analysis);
}

void AnalysisWindow::setBidData(const QVector<PriceQuantity> &supplierData,
                                const QVector<PriceQuantity> &consumerData)
{
    this->supplierData = supplierData;
    this->consumerData = consumerData;
}

double AnalysisWindow::calculateIntegral(const QVector<PriceQuantity> &data, double maxQuantity, bool isSupplier)
{
    double integral = 0.0;
    double currentQuantity = 0.0;

    for (const auto &item : data) {
        // 如果当前累计量已超过交点电量，则只计算到交点的部分
        if (currentQuantity >= maxQuantity)
            break;

        // 计算当前阶梯可计入的电量
        double availableQuantity = qMin(item.quantity, maxQuantity - currentQuantity);

        // 积分 = 价格 × 电量
        integral += item.price * availableQuantity;

        // 更新累计电量
        currentQuantity += item.quantity;
    }

    return integral;
}

void AnalysisWindow::on_billButton_clicked()
{
    if (intersectionPoint.x() < 0 || intersectionPoint.y() < 0) {
        QMessageBox::warning(this, "数据不足", "请先确保已生成有效交点！");
        return;
    }

    if (supplierData.isEmpty() || consumerData.isEmpty()) {
        QMessageBox::warning(this, "数据不足", "未获取到竞价数据！");
        return;
    }

    // 计算交点前的积分
    double consumerSpending = calculateIntegral(consumerData, intersectionPoint.x(), false);
    double supplierIncome = calculateIntegral(supplierData, intersectionPoint.x(), true);
    double socialWelfare = consumerSpending - supplierIncome;

    // 显示账单信息
    QString billInfo = QString("账单信息:\n\n");
    billInfo += QString("1. 客户端支出: %.2f 元\n").arg(consumerSpending);
    billInfo += QString("2. 供电端汇入: %.2f 元\n").arg(supplierIncome);
    billInfo += QString("3. 社会福祉: %.2f 元\n").arg(socialWelfare);

    QMessageBox::information(this, "账单查看", billInfo);
}
